package com.Classroom.al.controllers;


import com.Classroom.al.dao.ClassroomRepository;
import com.Classroom.al.entities.Classroom;
import com.Classroom.al.entities.Student;
import com.Classroom.al.services.ClassroomService;
import com.Classroom.al.services.StudenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("classrooms")
public class ClassroomController {
    @Autowired
    ClassroomService classroomService;

    @Autowired
    StudenService studenService;

    @GetMapping
    public String displayClassroom(Model model){
        List<Classroom> classrooms=classroomService.getAll();
        model.addAttribute("classrooms",classrooms);

        return "classrooms/list-classrooms";
    }
    @GetMapping("/new")

    public String displayClassroomForm(Model model){
        Classroom aClassroom=new Classroom();
        List<Student> students=studenService.getAll();
        model.addAttribute("classroom",aClassroom);
        model.addAttribute("allStudents",students);

        return "classrooms/new-classroom";
    }
    @PostMapping("/save")
    public String createClassroom(Model model, @RequestParam List<Long> students, Classroom classroom){
        //处理保存到数据库的行为

        classroomService.save(classroom);

        //使用重定位防止重复提交
        return "redirect:/classrooms";

    }

    @RequestMapping("/update/{id}")
    public String updateClassroom(@PathVariable("id") long id,Model model){
        Classroom classroomById = classroomService.getClassroomById(id);
        model.addAttribute("classroom",classroomById);
        List<Student> students=studenService.getAll();
        model.addAttribute("allStudents",students);
        return "/classrooms/update-classroom";


    }
    @RequestMapping("/update")
    public String update(Classroom classroom){
        classroomService.save(classroom);
        System.out.println(classroom);
        return "redirect:/classrooms";
    }

    @RequestMapping("/del/{id}")
    public String dClassroom(@PathVariable("id") long id){
       classroomService.getClassroomById(id);
        return "redirect:/students";
    }






}
